package com.example.server.common.config.auth;

import com.example.server.common.config.annotation.MustLogin;
import com.example.server.common.config.exception.TokenErrorException;
import com.example.server.common.config.exception.TokenExpireException;
import com.example.server.common.constant.CustomerConstants;
import com.example.server.common.constant.TokenConstants;
import com.example.server.common.utils.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author china.fuyao@outlook.com
 * @date 2020-03-25 15:49
 * @description
 */
@Slf4j
@Component
public class AccessInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    RedisUtil redisUtil;

    /**
     * 前置操作
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 接口拦截控制
        MustLogin mustLogin = method.getAnnotation(MustLogin.class);
        if (null != mustLogin) {
            if (mustLogin.isAdmin()) {
                return checkAdmin(request, response);
            }
            return checkAuth(request, response);
        }
        return true;
    }

    /**
     * 基础鉴权
     *
     * @param request
     * @param response
     * @return
     */
    private boolean checkAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (verifyToken(request)) {
            request.setAttribute("customerInfo", getUserInfo(request));
            return true;
        }
        throw new TokenExpireException("基础鉴权失败");
    }

    /**
     * token校验
     *
     * @param request
     * @return
     */
    private boolean verifyToken(HttpServletRequest request) {
        return jwtTokenUtil.validateToken(getToken(request));
    }

    /**
     * 管理鉴权
     *
     * @param request
     * @param response
     * @return
     */
    private boolean checkAdmin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (checkAuth(request, response)) {
            Integer authorities = getAuthorities(request);
            if (CustomerConstants.ADMIN_USER == authorities) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取用户权限列表
     *
     * @param request
     * @return
     */
    private Integer getAuthorities(HttpServletRequest request) {
        String token = getToken(request);
        return jwtTokenUtil.getAuthoritiesFromToken(token);
    }

    /**
     * 获取用户权限列表
     *
     * @param request
     * @return
     */
    private TokenUser getUserInfo(HttpServletRequest request) {
        String token = getToken(request);
        Integer customerId = jwtTokenUtil.getUserIdFromToken(token);
        String customerName = jwtTokenUtil.getUsernameFromToken(token);
        Integer authorities = jwtTokenUtil.getAuthoritiesFromToken(token);
        Integer status = jwtTokenUtil.getUserStatusFromToken(token);
        return new TokenUser(customerId, customerName, authorities, status);
    }

    protected String getToken(HttpServletRequest request) {
        String fullToken = request.getHeader(TokenConstants.HEADER_STRING);
        if (StringUtils.isNotBlank(fullToken)) {
            return fullToken;
        }
        throw new TokenExpireException("token为空");
    }

    /**
     * 后置操作
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

}
